package com.baozun.houji.me.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.viewModelScope
import com.afollestad.date.year
import com.alibaba.android.arouter.launcher.ARouter
import com.baozhun.mall.common.activity.WebContainerActivity
import com.baozhun.mall.common.arouter.RoutePath
import com.baozhun.mall.common.base.BaseActivity
import com.baozhun.mall.common.base.mEventViewModel
import com.baozhun.mall.common.ext.showToast
import com.baozhun.mall.common.model.enums.MainNavigateType
import com.baozhun.mall.common.model.enums.Sex
import com.baozhun.mall.common.util.CacheUtil
import com.baozhun.mall.common.util.Constants
import com.baozhun.mall.common.util.DialogUtil
import com.baozhun.mall.common.util.eventbus.EventBusUtils
import com.baozhun.mall.common.util.eventbus.EventCode
import com.baozhun.mall.common.widget.dialog.BirthDayChooseDialog
import com.baozhun.mall.common.widget.dialog.ChoosePhotoDialog
import com.baozhun.mall.common.widget.dialog.CommonChooseDialog
import com.baozun.houji.me.R
import com.baozun.houji.me.databinding.ActivitySetBinding
import com.baozun.houji.me.viewmodel.SetViewModel
import com.blankj.utilcode.util.TimeUtils
import com.bumptech.glide.Glide
import com.hjq.bar.OnTitleBarListener
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.permissions.PermissionChecker
import com.lxj.xpopup.XPopup
import com.lxj.xpopupext.listener.TimePickerListener
import com.zzhoujay.richtext.RichText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Calendar
import java.util.Date


/**
 * @Title：设置页面
 * @Description：
 * @Author：xuefeng.zhu
 * @Since：2022/11/17
 * @Version：1.0.0
 */
class SetActivity : BaseActivity<SetViewModel, ActivitySetBinding>(), OnTitleBarListener {
    /**
     * 是否有更新，无更新直接退出当前页面
     */
    private var mHasUpdate: Boolean = false

    companion object {
        const val REQUEST_CODE_UPDATE_NICK_NAME = 10
        fun start(context: Context) {
            var intent = Intent(context, SetActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.mUserInfo.value = CacheUtil.getUser()
        mViewModel.mCacheSize.value = CacheUtil.getGlideCacheSize(this)
    }

    override fun createObserver() {
        super.createObserver()
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when (v?.id) {
            R.id.ll_my_avatar -> { //我的头像
                if (PermissionChecker.isCheckReadStorage(SelectMimeType.ofImage(), this) && PermissionChecker.isCheckCamera(this)) {
                    ChoosePhotoDialog(this) {
                        mHasUpdate = true
                        mViewModel.mUserInfo.value?.photo = it
                        mViewModel.mUserInfo.value = mViewModel.mUserInfo.value
                    }.show()
                } else {
                    DialogUtil.showConfirmDialog(this, getString(com.baozhun.mall.res.R.string.request_camera_permission_hint)) {
                        ChoosePhotoDialog(this) {
                            mHasUpdate = true
                            mViewModel.mUserInfo.value?.photo = it
                            mViewModel.mUserInfo.value = mViewModel.mUserInfo.value
                        }.show()
                    }
                }
            }

            R.id.ll_my_nickname -> { //我的昵称
                UpdateNickNameActivity.startForResult(this, REQUEST_CODE_UPDATE_NICK_NAME, mViewModel.mUserInfo.value?.nickname.toString())
            }

            R.id.ll_sex -> { //我的性别
                CommonChooseDialog(
                    this,
                    com.baozhun.mall.res.R.string.please_choose_sex,
                    mViewModel.mUserInfo.value?.getSexDesc(),
                    arrayListOf(Sex.MAN.sexDesc, Sex.WOMEN.sexDesc)
                ) { selectItem: String, selectPosition: Int ->
                    mHasUpdate = true
                    mViewModel.mUserInfo.value?.sex = Sex.values().find { it.sexDesc == selectItem }?.tag!!
                    mViewModel.mUserInfo.value = mViewModel.mUserInfo.value
                }.show()
            }

            R.id.ll_birthday -> { //我的生日
                showBirthdayDialog()
            }

            R.id.ll_my_receive_address -> {
                ARouter.getInstance().build(RoutePath.Me.ADDRESS_LIST).navigation()
            }

            R.id.ll_auth_and_un_auth -> { //授信与解除授信
                if (CacheUtil.getUser().credit_success == true) {
                    ARouter.getInstance().build(RoutePath.Home.UN_AUTH).navigation()
                } else {
                    ARouter.getInstance().build(RoutePath.Home.INTEGRAL_AUTH).navigation()
                }
            }

            R.id.ll_clear_cache -> { //清楚缓存
                mViewModel.viewModelScope.launch(Dispatchers.IO) {
                    Glide.get(this@SetActivity).clearDiskCache()
                }
                RichText.recycle()
                showToast(com.baozhun.mall.res.R.string.clear_cache_success)
                mViewModel.mCacheSize.value = "0M"
            }

            R.id.ll_version_code -> { //版本信息

            }

            R.id.ll_delete_account -> { //注销账号
                DialogUtil.showConfirmDialog(this, getString(com.baozhun.mall.res.R.string.delete_account_hint)) {
                    showToast(com.baozhun.mall.res.R.string.apply_submitted)
                }
            }

            R.id.tv_exit_login -> {  //退出登录
                DialogUtil.showConfirmDialog(this, getString(com.baozhun.mall.res.R.string.login_out_hint)) {
                    finish()
                    mEventViewModel.switchTabEvent.value = MainNavigateType.HOME.ordinal
                    CacheUtil.clearUserInfo()
                    EventBusUtils.sendEvent(EventCode.LOG_OUT)
                }

            }

            R.id.ll_privacy_agreement -> {  //隐私协议
                WebContainerActivity.start(this, Constants.Url.PRIVACY_PROTOCOL, getString(com.baozhun.mall.res.R.string.privacy_agreement))

            }

            R.id.ll_user_agreement -> {   //用户协议
                WebContainerActivity.start(this, Constants.Url.USER_PROTOCOL, getString(com.baozhun.mall.res.R.string.user_agreement))
            }

        }
    }

    override fun finish() {
        //兼容退出登陆的情况
        if (CacheUtil.isLogin() && mHasUpdate) {
            mViewModel.updateUserInfo {
                super.finish()
            }
        } else {
            super.finish()
        }
    }


    /**
     * Wed Dec 20 11:09:25 GMT+08:00 2023
     * 显示生日选择对话框
     */
    private fun showBirthdayDialog() {
        val selectCalendar = Calendar.getInstance()
        val currentData: Date? = TimeUtils.string2Date(mViewModel.mUserInfo.value?.birthday, Constants.Common.YYYY_MM_DD_FORMAT)
        if (currentData != null) {
            selectCalendar.time = currentData
        }
        val timePickerPopup = BirthDayChooseDialog(this)
            .setDateRange(Calendar.getInstance().apply { year = 1900 }, Calendar.getInstance())
            .setYearRange(1900, Calendar.getInstance().year)
            .setDefaultDate(selectCalendar)
            .setTimePickerListener(object : TimePickerListener {
                override fun onTimeChanged(date: Date?) {
                }

                override fun onTimeConfirm(date: Date, view: View?) {
                    mHasUpdate = true
                    mViewModel.mUserInfo.value?.birthday = TimeUtils.date2String(date, Constants.Common.YYYY_MM_DD_FORMAT)
                    mViewModel.mUserInfo.value = mViewModel.mUserInfo.value
                }

                override fun onCancel() {
                }
            })
        XPopup.Builder(this)
            .asCustom(timePickerPopup)
            .show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        when (requestCode) {
            REQUEST_CODE_UPDATE_NICK_NAME -> {
                mHasUpdate = true
                mViewModel.mUserInfo.value?.nickname = data?.getStringExtra(Constants.Common.BUNDLE_NAME).toString()
                mViewModel.mUserInfo.value = mViewModel.mUserInfo.value
            }
        }
    }
}